<script setup>
import AuthenticatedLayout from '@/Layouts/AuthenticatedLayout.vue';
import { Head, Link, useForm, router } from '@inertiajs/vue3';
import { ref, computed } from 'vue';

const props = defineProps({
    keyword: String,
    type: String,
    results: Object,
    filters: Object,
});

const searchForm = useForm({
    q: props.keyword || '',
    type: props.type || 'all',
});

const activeTab = ref(props.type || 'all');

const tabs = [
    { key: 'all', label: '全部' },
    { key: 'posts', label: '帖子' },
    { key: 'bars', label: '贴吧' },
    { key: 'users', label: '用户' },
];

const handleSearch = () => {
    if (!searchForm.q.trim()) {
        return;
    }
    router.get(route('search.index'), {
        q: searchForm.q,
        type: searchForm.type,
    }, {
        preserveState: true,
        preserveScroll: true,
    });
};

const switchTab = (tab) => {
    activeTab.value = tab;
    searchForm.type = tab;
    if (searchForm.q.trim()) {
        handleSearch();
    }
};

const formatNumber = (num) => {
    if (num >= 10000) {
        return (num / 10000).toFixed(1) + '万';
    }
    return num.toString();
};

const formatTime = (time) => {
    if (!time) return '';
    const date = new Date(time);
    const now = new Date();
    const diff = now - date;
    const minutes = Math.floor(diff / 60000);
    const hours = Math.floor(diff / 3600000);
    const days = Math.floor(diff / 86400000);

    if (minutes < 1) return '刚刚';
    if (minutes < 60) return `${minutes}分钟前`;
    if (hours < 24) return `${hours}小时前`;
    if (days < 7) return `${days}天前`;
    return date.toLocaleDateString('zh-CN');
};

const getUserAvatar = (user) => {
    if (user?.avatar) {
        return user.avatar.startsWith('http') ? user.avatar : `/storage/${user.avatar}`;
    }
    return `https://api.dicebear.com/7.x/avataaars/svg?seed=${user?.name || 'user'}`;
};

const getBarAvatar = (bar) => {
    if (bar.avatar) {
        return bar.avatar.startsWith('http') ? bar.avatar : `/storage/${bar.avatar}`;
    }
    return `https://api.dicebear.com/7.x/shapes/svg?seed=${bar.name}`;
};

const highlightKeyword = (text, keyword) => {
    if (!text || !keyword) return text;
    const regex = new RegExp(`(${keyword})`, 'gi');
    return text.replace(regex, '<mark class="bg-yellow-200">$1</mark>');
};
</script>

<template>
    <Head title="搜索" />

    <AuthenticatedLayout>
        <div class="space-y-6">
            <!-- 搜索框 -->
            <div class="bg-card text-card-foreground flex flex-col gap-6 rounded-xl border py-6 shadow-sm">
                <div class="px-6">
                    <form @submit.prevent="handleSearch" class="max-w-2xl mx-auto">
                        <div class="relative">
                            <svg class="absolute left-4 top-1/2 -translate-y-1/2 h-5 w-5 text-muted-foreground" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z" />
                            </svg>
                            <input
                                v-model="searchForm.q"
                                type="text"
                                placeholder="搜索贴吧、帖子、用户..."
                                class="w-full pl-12 pr-4 py-3 border border-input rounded-lg bg-background text-base placeholder:text-muted-foreground focus:outline-none focus:ring-2 focus:ring-primary focus:border-primary transition-all"
                                autofocus
                            />
                        </div>
                    </form>
                </div>
            </div>

            <!-- 搜索结果 -->
            <div v-if="keyword" class="space-y-6">
                <!-- 标签页 -->
                <div class="bg-card text-card-foreground flex flex-col gap-6 rounded-xl border py-6 shadow-sm">
                    <div class="px-6">
                        <div class="flex items-center gap-2 border-b">
                            <button
                                v-for="tab in tabs"
                                :key="tab.key"
                                @click="switchTab(tab.key)"
                                :class="[
                                    'px-4 py-2 text-sm font-medium border-b-2 transition-colors',
                                    activeTab === tab.key
                                        ? 'border-primary text-primary'
                                        : 'border-transparent text-muted-foreground hover:text-foreground'
                                ]"
                            >
                                {{ tab.label }}
                            </button>
                        </div>
                    </div>
                </div>

                <!-- 帖子结果 -->
                <div v-if="(activeTab === 'all' || activeTab === 'posts') && results.posts" class="bg-card text-card-foreground flex flex-col gap-6 rounded-xl border py-6 shadow-sm">
                    <div class="px-6">
                        <h2 class="text-xl font-bold mb-4">帖子 ({{ formatNumber(results.posts.total || 0) }})</h2>
                        <div v-if="results.posts.data && results.posts.data.length > 0" class="space-y-4">
                            <div
                                v-for="post in results.posts.data"
                                :key="post.id"
                                class="p-4 border rounded-lg hover:bg-muted/50 transition-colors"
                            >
                                <div class="flex items-start gap-4">
                                    <Link :href="route('bars.show', post.bar?.slug)" class="flex-shrink-0">
                                        <img
                                            :src="getBarAvatar(post.bar)"
                                            :alt="post.bar?.name"
                                            class="w-10 h-10 rounded-lg"
                                        />
                                    </Link>
                                    <div class="flex-1 min-w-0">
                                        <div class="flex items-center gap-2 mb-1">
                                            <Link
                                                :href="route('bars.show', post.bar?.slug)"
                                                class="text-sm text-primary hover:underline"
                                            >
                                                {{ post.bar?.name }}
                                            </Link>
                                            <span class="text-xs text-muted-foreground">·</span>
                                            <Link
                                                :href="route('users.show', post.user?.username || post.user?.id)"
                                                class="text-sm text-muted-foreground hover:underline"
                                            >
                                                {{ post.user?.nickname || post.user?.name }}
                                            </Link>
                                            <span class="text-xs text-muted-foreground">·</span>
                                            <span class="text-xs text-muted-foreground">{{ formatTime(post.created_at) }}</span>
                                        </div>
                                        <Link
                                            :href="route('posts.show', post.slug)"
                                            class="block"
                                        >
                                            <h3 class="text-base font-semibold mb-1 hover:text-primary transition-colors" v-html="highlightKeyword(post.title, keyword)"></h3>
                                            <p class="text-sm text-muted-foreground line-clamp-2" v-html="highlightKeyword(post.content.substring(0, 150), keyword)"></p>
                                        </Link>
                                        <div class="flex items-center gap-4 mt-2 text-xs text-muted-foreground">
                                            <span>浏览 {{ formatNumber(post.views || 0) }}</span>
                                            <span>点赞 {{ formatNumber(post.like_count || 0) }}</span>
                                            <span>回复 {{ formatNumber(post.reply_count || 0) }}</span>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div v-else class="text-center py-12 text-muted-foreground">
                            <p>未找到相关帖子</p>
                        </div>

                        <!-- 分页 -->
                        <div v-if="results.posts.links && results.posts.links.length > 3 && activeTab === 'posts'" class="flex items-center justify-center gap-2 pt-6">
                            <Link
                                v-for="(link, index) in results.posts.links"
                                :key="index"
                                :href="link.url || '#'"
                                v-html="link.label"
                                :class="[
                                    'inline-flex items-center justify-center whitespace-nowrap rounded-md text-sm font-medium transition-all h-9 px-3 py-2',
                                    link.active ? 'bg-primary text-primary-foreground shadow-sm' : 'border border-input bg-background shadow-sm hover:bg-accent hover:text-accent-foreground',
                                    !link.url ? 'text-muted-foreground cursor-not-allowed opacity-50' : ''
                                ]"
                            />
                        </div>
                    </div>
                </div>

                <!-- 贴吧结果 -->
                <div v-if="(activeTab === 'all' || activeTab === 'bars') && results.bars" class="bg-card text-card-foreground flex flex-col gap-6 rounded-xl border py-6 shadow-sm">
                    <div class="px-6">
                        <h2 class="text-xl font-bold mb-4">贴吧 ({{ formatNumber(results.bars.total || 0) }})</h2>
                        <div v-if="results.bars.data && results.bars.data.length > 0" class="space-y-4">
                            <div
                                v-for="bar in results.bars.data"
                                :key="bar.id"
                                class="p-4 border rounded-lg hover:bg-muted/50 transition-colors"
                            >
                                <Link :href="route('bars.show', bar.slug)" class="flex items-center gap-4">
                                    <img
                                        :src="getBarAvatar(bar)"
                                        :alt="bar.name"
                                        class="w-16 h-16 rounded-lg flex-shrink-0"
                                    />
                                    <div class="flex-1 min-w-0">
                                        <h3 class="text-lg font-semibold mb-1 hover:text-primary transition-colors" v-html="highlightKeyword(bar.name, keyword)"></h3>
                                        <p v-if="bar.description" class="text-sm text-muted-foreground line-clamp-2 mb-2" v-html="highlightKeyword(bar.description, keyword)"></p>
                                        <div class="flex items-center gap-4 text-xs text-muted-foreground">
                                            <span>{{ formatNumber(bar.member_count || 0) }} 成员</span>
                                            <span>{{ formatNumber(bar.post_count || 0) }} 帖子</span>
                                            <span>吧主：{{ bar.owner?.nickname || bar.owner?.name }}</span>
                                        </div>
                                    </div>
                                </Link>
                            </div>
                        </div>
                        <div v-else class="text-center py-12 text-muted-foreground">
                            <p>未找到相关贴吧</p>
                        </div>

                        <!-- 分页 -->
                        <div v-if="results.bars.links && results.bars.links.length > 3 && activeTab === 'bars'" class="flex items-center justify-center gap-2 pt-6">
                            <Link
                                v-for="(link, index) in results.bars.links"
                                :key="index"
                                :href="link.url || '#'"
                                v-html="link.label"
                                :class="[
                                    'inline-flex items-center justify-center whitespace-nowrap rounded-md text-sm font-medium transition-all h-9 px-3 py-2',
                                    link.active ? 'bg-primary text-primary-foreground shadow-sm' : 'border border-input bg-background shadow-sm hover:bg-accent hover:text-accent-foreground',
                                    !link.url ? 'text-muted-foreground cursor-not-allowed opacity-50' : ''
                                ]"
                            />
                        </div>
                    </div>
                </div>

                <!-- 用户结果 -->
                <div v-if="(activeTab === 'all' || activeTab === 'users') && results.users" class="bg-card text-card-foreground flex flex-col gap-6 rounded-xl border py-6 shadow-sm">
                    <div class="px-6">
                        <h2 class="text-xl font-bold mb-4">用户 ({{ formatNumber(results.users.total || 0) }})</h2>
                        <div v-if="results.users.data && results.users.data.length > 0" class="space-y-4">
                            <div
                                v-for="user in results.users.data"
                                :key="user.id"
                                class="p-4 border rounded-lg hover:bg-muted/50 transition-colors"
                            >
                                <Link :href="route('users.show', user.username || user.id)" class="flex items-center gap-4">
                                    <img
                                        :src="getUserAvatar(user)"
                                        :alt="user.nickname || user.name"
                                        class="w-12 h-12 rounded-full flex-shrink-0"
                                    />
                                    <div class="flex-1 min-w-0">
                                        <h3 class="text-base font-semibold mb-1 hover:text-primary transition-colors" v-html="highlightKeyword(user.nickname || user.name, keyword)"></h3>
                                        <p v-if="user.signature" class="text-sm text-muted-foreground line-clamp-1 mb-2">{{ user.signature }}</p>
                                        <div class="flex items-center gap-4 text-xs text-muted-foreground">
                                            <span>Lv.{{ user.level || 1 }}</span>
                                            <span>{{ formatNumber(user.posts_count || 0) }} 帖子</span>
                                            <span>{{ formatNumber(user.followers_count || 0) }} 粉丝</span>
                                        </div>
                                    </div>
                                </Link>
                            </div>
                        </div>
                        <div v-else class="text-center py-12 text-muted-foreground">
                            <p>未找到相关用户</p>
                        </div>

                        <!-- 分页 -->
                        <div v-if="results.users.links && results.users.links.length > 3 && activeTab === 'users'" class="flex items-center justify-center gap-2 pt-6">
                            <Link
                                v-for="(link, index) in results.users.links"
                                :key="index"
                                :href="link.url || '#'"
                                v-html="link.label"
                                :class="[
                                    'inline-flex items-center justify-center whitespace-nowrap rounded-md text-sm font-medium transition-all h-9 px-3 py-2',
                                    link.active ? 'bg-primary text-primary-foreground shadow-sm' : 'border border-input bg-background shadow-sm hover:bg-accent hover:text-accent-foreground',
                                    !link.url ? 'text-muted-foreground cursor-not-allowed opacity-50' : ''
                                ]"
                            />
                        </div>
                    </div>
                </div>

                <!-- 无结果提示 -->
                <div v-if="activeTab === 'all' && (!results.posts || results.posts.total === 0) && (!results.bars || results.bars.total === 0) && (!results.users || results.users.total === 0)" class="bg-card text-card-foreground flex flex-col gap-6 rounded-xl border py-12 shadow-sm">
                    <div class="px-6 text-center text-muted-foreground">
                        <p class="text-lg mb-2">未找到相关结果</p>
                        <p class="text-sm">尝试使用其他关键词搜索</p>
                    </div>
                </div>
            </div>

            <!-- 未搜索时显示 -->
            <div v-else class="bg-card text-card-foreground flex flex-col gap-6 rounded-xl border py-12 shadow-sm">
                <div class="px-6 text-center text-muted-foreground">
                    <p class="text-lg mb-2">输入关键词开始搜索</p>
                    <p class="text-sm">支持搜索帖子、贴吧、用户</p>
                </div>
            </div>
        </div>
    </AuthenticatedLayout>
</template>

